/**
 * 代理管理模块
 */
const ProxyModule = {
    // 当前编辑的代理ID
    currentEditingProxyId: null,
    // 当前管理界面的layer索引
    currentManagementLayerIndex: null,
    // 代理数据缓存
    proxiesCache: [],
    
    /**
     * 显示代理管理界面
     */
    showProxyManagement: async function() {
        try {
            const proxies = await this.loadProxies();
            this.proxiesCache = proxies; // 缓存数据
            const html = this.renderProxyManagementUI(proxies);
            
            // 判断设备类型
            const width = window.innerWidth;
            const isMobileOrTablet = width <= 1400;
            
            const index = layer.open({
                type: 1,
                title: '代理管理',
                content: html,
                area: isMobileOrTablet ? ['100%', '100%'] : ['900px', '600px'],
                btn: ['添加代理', '导入代理链接', 'Sing-box管理', '关闭'],
                btnAlign: 'c',
                btn1: function() {
                    ProxyModule.showAddProxyModal();
                    return false; // 阻止关闭
                },
                btn2: function() {
                    ProxyModule.showImportV2RayModal();
                    return false; // 阻止关闭
                },
                btn3: function() {
                    ProxyModule.showSingboxManagement();
                    return false; // 阻止关闭
                },
                success: function() {
                   // 渲染表格
                   ProxyModule.renderTable(proxies);
               }
            });
            
            // 保存当前窗口索引
            this.currentManagementLayerIndex = index;
        } catch (error) {
            console.error('显示代理管理界面失败:', error);
            layer.msg('加载代理管理界面失败', { icon: 2 });
        }
    },
    
    /**
     * 加载代理列表
     */
    loadProxies: async function() {
        try {
            const response = await Api.apiRequest('/proxies');
            return response || [];
        } catch (error) {
            console.error('加载代理列表失败:', error);
            return [];
        }
    },
    
    /**
     * 渲染代理管理界面
     */
    renderProxyManagementUI: function(proxies) {
        // 使用 layui.table.render，只需要一个容器
        return `
            <div style="padding: 15px;">
                <table id="proxy-table" lay-filter="proxy-table"></table>
            </div>
            <script type="text/html" id="proxy-name-tpl">
                <strong>{{ d.name }}</strong>
                {{# if(d.is_shared && d.is_own){ }}
                    <span style="color: #FFB800; margin-left: 5px;" title="已共享给其他用户">🔗分享</span>
                {{# } else if(!d.is_own) { }}
                    <span style="color: #999; margin-left: 5px;" title="他人共享">🔗共享</span>
                {{# } }}
            </script>
            <script type="text/html" id="proxy-type-tpl">
                <span class="layui-badge layui-bg-blue">{{ (d.type || d.proxy_type).toUpperCase() }}</span>
            </script>
            <script type="text/html" id="proxy-latency-tpl">
                {{# if(d.latency){ }}
                    <span style="color: {{ d.latency < 200 ? '#5FB878' : (d.latency < 500 ? '#FFB800' : '#FF5722') }}; font-weight: bold;">{{ d.latency }}ms</span>
                {{# } else { }}
                    <span style="color: #999;">未测试</span>
                {{# } }}
            </script>
            <script type="text/html" id="proxy-status-tpl">
                {{# if(d.is_active){ }}
                    <span style="color: #5FB878;">●</span> 启用
                {{# } else { }}
                    <span style="color: #999;">●</span> 禁用
                {{# } }}
            </script>
            <script type="text/html" id="proxy-actions-tpl">
                <button class="layui-btn layui-btn-xs" lay-event="test">测试</button>
                {{# if(d.is_own){ }}
                    <button class="layui-btn layui-btn-xs" lay-event="copy">复制</button>
                    <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">编辑</button>
                    <button class="layui-btn layui-btn-xs {{ d.is_shared ? 'layui-btn-warm' : 'layui-btn-primary' }}" lay-event="toggle-share">{{ d.is_shared ? '取消分享' : '分享' }}</button>
                    <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>
                {{# } }}
            </script>
        `;
    },
    
    /**
     * 绑定代理事件
     */
    bindProxyEvents: function() {
        // 使用事件委托
        $('button[data-action]').off('click').on('click', function() {
            const action = $(this).data('action');
            const proxyId = $(this).data('id');
            
            switch(action) {
                case 'test':
                    ProxyModule.testProxy(proxyId);
                    break;
                case 'edit':
                   const proxyToEdit = ProxyModule.proxiesCache.find(p => p.id === proxyId);
                   ProxyModule.editProxy(proxyToEdit);
                   break;
                case 'toggle-share':
                    ProxyModule.toggleShare(proxyId);
                    break;
                case 'delete':
                    ProxyModule.deleteProxy(proxyId);
                    break;
            }
        });
    },
    
    /**
     * 显示添加代理弹窗
     */
    showAddProxyModal: function() {
        this.showProxyModal();
    },
    
    /**
     * 显示代理编辑/添加弹窗
     */
    showProxyModal: function(proxy = null) {
        const isEdit = !!proxy;
        const formId = isEdit ? 'edit-proxy-form' : 'add-proxy-form';
        
        // 判断是否为V2Ray类型代理
        const v2rayTypes = ['vmess', 'vless', 'trojan', 'shadowsocks', 'hysteria', 'hysteria2'];
        const isV2RayProxy = isEdit && v2rayTypes.includes(proxy.type || proxy.proxy_type);
        
        // V2Ray代理的配置链接已经在列表数据中
        const proxyLink = (isV2RayProxy && proxy.config_link) ? proxy.config_link : '';
        
        let formHtml = `<div style="padding: 20px;"><form class="layui-form" id="${formId}" lay-filter="${formId}">`;
        
        // 名称字段（所有类型都需要）
        formHtml += `
            <div class="layui-form-item">
                <label class="layui-form-label">代理名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="例如：美国代理1" class="layui-input" value="${isEdit ? escapeHtml(proxy.name) : ''}">
                </div>
            </div>
        `;
        
        if (isV2RayProxy) {
            // V2Ray类型代理：只显示名称和配置链接
            formHtml += `
                <div class="layui-form-item">
                    <label class="layui-form-label">代理类型</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input layui-disabled" disabled value="${(proxy.type || proxy.proxy_type).toUpperCase()}">
                        <input type="hidden" name="type" value="${proxy.type || proxy.proxy_type}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">配置链接</label>
                    <div class="layui-input-block">
                        <textarea name="proxy_link" class="layui-textarea" rows="3" placeholder="粘贴新的配置链接以更新代理配置">${escapeHtml(proxyLink)}</textarea>
                        <div style="color: #999; font-size: 12px; margin-top: 5px;">
                            <i class="layui-icon layui-icon-tips"></i> 如需修改配置，请粘贴新的配置链接
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="is_active" lay-skin="switch" lay-text="启用|禁用" ${proxy.is_active ? 'checked' : ''}>
                    </div>
                </div>
            `;
        } else {
            // SOCKS5/HTTP类型：显示完整表单
            formHtml += `
                <div class="layui-form-item">
                    <label class="layui-form-label">代理类型</label>
                    <div class="layui-input-block">
                        <select name="type" lay-verify="required" ${isEdit ? 'disabled' : ''}>
                            <option value="socks5" ${isEdit && (proxy.type === 'socks5' || proxy.proxy_type === 'socks5') ? 'selected' : ''}>SOCKS5</option>
                            <option value="http" ${isEdit && (proxy.type === 'http' || proxy.proxy_type === 'http') ? 'selected' : ''}>HTTP</option>
                        </select>
                        ${isEdit ? `<input type="hidden" name="type" value="${proxy.type || proxy.proxy_type}">` : ''}
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">服务器地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="host" required lay-verify="required" placeholder="例如：127.0.0.1" class="layui-input" value="${isEdit ? escapeHtml(proxy.host) : ''}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">端口</label>
                    <div class="layui-input-block">
                        <input type="number" name="port" required lay-verify="required" placeholder="例如：1080" class="layui-input" value="${isEdit ? proxy.port : ''}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" placeholder="可选" class="layui-input" value="${isEdit && proxy.username ? escapeHtml(proxy.username) : ''}">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" placeholder="可选" class="layui-input" value="${isEdit && proxy.password ? escapeHtml(proxy.password) : ''}">
                    </div>
                </div>
                ${isEdit ? `
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="is_active" lay-skin="switch" lay-text="启用|禁用" ${proxy.is_active ? 'checked' : ''}>
                    </div>
                </div>
                ` : ''}
            `;
        }
        
        formHtml += `</form></div>`;
        
        // 判断设备类型
        const width = window.innerWidth;
        const isMobileOrTablet = width <= 1400;
        
        const editIndex = layer.open({
            type: 1,
            title: isEdit ? '编辑代理' : '添加代理',
            content: formHtml,
            area: isMobileOrTablet ? ['100%', '100%'] : ['500px', 'auto'],
            btn: [isEdit ? '保存' : '添加', '取消'],
            btnAlign: 'c',
            yes: function(index) {
                const formData = layui.form.val(formId);
                if (isEdit) {
                    ProxyModule.handleUpdateProxy(proxy.id, formData, index);
                } else {
                    ProxyModule.handleAddProxy(formData, index);
                }
            },
            success: function() {
                layui.form.render(null, formId);
            }
        });
    },
    
    /**
     * 处理添加代理
     */
    handleAddProxy: async function(formData, addLayerIndex) {
        const loadingIndex = layer.load(1);
        try {
            const proxyData = {
                name: formData.name,
                type: formData.type || formData.proxy_type,
                host: formData.host,
                port: parseInt(formData.port),
                username: formData.username || null,
                password: formData.password || null
            };
            
            await Api.apiRequest('/proxies', {
                method: 'POST',
                body: JSON.stringify(proxyData)
            });
            
            layer.close(loadingIndex);
            // 只关闭添加弹窗，不关闭代理列表页
            if (addLayerIndex) {
                layer.close(addLayerIndex);
            }
            layer.msg('代理添加成功', { icon: 1 });
            // 刷新列表
            this.refreshProxyList();
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('添加失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },
    
    /**
     * 编辑代理
     */
    editProxy: function(proxy) {
       if (proxy) {
           this.showProxyModal(proxy);
       } else {
           layer.msg('加载代理信息失败', { icon: 2 });
       }
   },
   
   /**
    * 复制代理
    */
   copyProxy: function(proxyId) {
       const proxyToCopy = this.proxiesCache.find(p => p.id === proxyId);
       if (proxyToCopy) {
           // 创建一个副本，移除id，并修改名称
           const copiedProxy = { ...proxyToCopy };
           delete copiedProxy.id;
           delete copiedProxy.is_shared; // 复制的代理不应该是共享状态
           copiedProxy.name = copiedProxy.name + ' (副本)';
           this.showProxyModal(copiedProxy);
       } else {
           layer.msg('找不到要复制的代理', { icon: 2 });
       }
   },
    
    /**
     * 处理更新代理
     */
    handleUpdateProxy: async function(proxyId, formData, editLayerIndex) {
        const loadingIndex = layer.load(1);
        try {
            // 检查是否有配置链接字段（V2Ray类型代理）
            const v2rayTypes = ['vmess', 'vless', 'trojan', 'shadowsocks', 'hysteria', 'hysteria2'];
            const proxyType = formData.type || formData.proxy_type;
            const isV2RayType = v2rayTypes.includes(proxyType);
            const hasProxyLink = formData.proxy_link && formData.proxy_link.trim();
            
            if (isV2RayType && hasProxyLink) {
                // V2Ray类型且提供了新的配置链接，需要重新导入
                const link = formData.proxy_link.trim();
                
                // 先删除旧代理
                await Api.apiRequest(`/proxies/${proxyId}`, {
                    method: 'DELETE'
                });
                
                // 导入新配置
                const importResponse = await Api.apiRequest('/proxies/import-v2ray', {
                    method: 'POST',
                    body: JSON.stringify({ v2ray_link: link })
                });
                
                // 更新名称和状态
                if (importResponse.id) {
                    await Api.apiRequest(`/proxies/${importResponse.id}`, {
                        method: 'PUT',
                        body: JSON.stringify({
                            name: formData.name,
                            is_active: formData.is_active === 'on'
                        })
                    });
                }
            } else if (isV2RayType) {
                // V2Ray类型但没有更新配置链接，只更新名称和状态
                const proxyData = {
                    name: formData.name,
                    is_active: formData.is_active === 'on'
                };
                
                await Api.apiRequest(`/proxies/${proxyId}`, {
                    method: 'PUT',
                    body: JSON.stringify(proxyData)
                });
            } else {
                // SOCKS5/HTTP类型，更新所有字段
                const proxyData = {
                    name: formData.name,
                    type: proxyType,
                    host: formData.host,
                    port: parseInt(formData.port),
                    username: formData.username || null,
                    password: formData.password || null,
                    is_active: formData.is_active === 'on'
                };
                
                await Api.apiRequest(`/proxies/${proxyId}`, {
                    method: 'PUT',
                    body: JSON.stringify(proxyData)
                });
            }
            
            layer.close(loadingIndex);
            // 只关闭编辑弹窗，不关闭代理列表页
            if (editLayerIndex) {
                layer.close(editLayerIndex);
            }
            layer.msg('代理更新成功', { icon: 1 });
            // 刷新列表
            this.refreshProxyList();
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('更新失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },
    
    /**
     * 测试代理延迟
     */
    testProxy: async function(proxyId) {
        const loadingIndex = layer.msg('正在测试代理...', { icon: 16, time: 0 });
        try {
            const response = await Api.apiRequest(`/proxies/${proxyId}/test`, {
                method: 'POST'
            });
            
            layer.close(loadingIndex);
            layer.msg(response.msg || '测试成功', { icon: 1 });
            // 刷新列表
            this.refreshProxyList();
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('测试失败: ' + (error.detail || error.message), { icon: 2, time: 3000 });
        }
    },
    
    /**
     * 删除代理
     */
    deleteProxy: async function(proxyId) {
        layer.confirm('确定要删除这个代理吗？', { icon: 3 }, async function(index) {
            layer.close(index);
            const loadingIndex = layer.load(1);
            try {
                await Api.apiRequest(`/proxies/${proxyId}`, {
                    method: 'DELETE'
                });
                
                layer.close(loadingIndex);
                layer.msg('代理已删除', { icon: 1 });
                // 刷新列表
                ProxyModule.refreshProxyList();
            } catch (error) {
                layer.close(loadingIndex);
                layer.msg('删除失败: ' + (error.detail || error.message), { icon: 2 });
            }
        });
    },
    
    /**
     * 切换代理共享状态
     */
    toggleShare: async function(proxyId) {
        const loadingIndex = layer.load(1);
        try {
            const response = await Api.apiRequest(`/proxies/${proxyId}/toggle-share`, {
                method: 'POST'
            });
            
            layer.close(loadingIndex);
            layer.msg(response.msg || '操作成功', { icon: 1 });
            // 刷新列表
            this.refreshProxyList();
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('操作失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },
    
    /**
     * 刷新代理列表（不重新打开窗口）
     */
    refreshProxyList: async function() {
        try {
            const proxies = await this.loadProxies();
            this.proxiesCache = proxies; // 更新缓存
            
            // 如果表格实例存在，则重载数据
            if (this.proxyTableInstance) {
                this.proxyTableInstance.reload({
                    data: this.prepareTableData(proxies)
                });
            } else {
                // 否则，重新渲染整个UI（仅在初次或窗口关闭后）
                if (!this.currentManagementLayerIndex) {
                    this.showProxyManagement();
                } else {
                    const layerElement = $('#layui-layer' + this.currentManagementLayerIndex);
                    if (layerElement.length) {
                        const html = this.renderProxyManagementUI(proxies);
                        layerElement.find('.layui-layer-content').html(html);
                        this.renderTable(proxies);
                    } else {
                         this.showProxyManagement();
                    }
                }
            }
        } catch (error) {
            console.error('刷新代理列表失败:', error);
            layer.msg('刷新列表失败', { icon: 2 });
        }
    },
    
    /**
     * 准备表格所需的数据格式
     */
    prepareTableData: function(proxies) {
        const currentUserId = Api.getCurrentUserId();
        return proxies.map(p => ({
            ...p,
            is_own: p.user_id === currentUserId
        }));
    },
    
    /**
     * 渲染layui表格
     */
    renderTable: function(proxies) {
        const tableData = this.prepareTableData(proxies);
        
        this.proxyTableInstance = layui.table.render({
            elem: '#proxy-table',
            data: tableData,
            lineStyle: 'height: 76px;',
            height: 'full',
            cols: [[
                { field: 'name', title: '名称', templet: '#proxy-name-tpl', minWidth: 200 },
                { field: 'latency', title: '延迟', templet: '#proxy-latency-tpl', width: 100, align: 'center' },
                { field: 'is_active', title: '状态', templet: '#proxy-status-tpl', width: 90, align: 'center' },
                { field: 'type', title: '类型', templet: '#proxy-type-tpl', width: 100, align: 'center' },
                { field: 'host', title: '地址', templet: d => `${escapeHtml(d.host)}:${d.port}` },
                { title: '操作', templet: '#proxy-actions-tpl', width: 320, align: 'center', fixed: 'right' }
            ]],
            skin: 'line',
            limit: proxies.length
        });

        // 绑定表格事件
        layui.table.on('tool(proxy-table)', (obj) => {
            const data = obj.data;
            const event = obj.event;
            
            switch(event) {
                case 'test':
                    this.testProxy(data.id);
                    break;
                case 'edit':
                    this.editProxy(data);
                    break;
                case 'copy':
                    this.copyProxy(data.id);
                    break;
                case 'toggle-share':
                    this.toggleShare(data.id);
                    break;
                case 'delete':
                    this.deleteProxy(data.id);
                    break;
            }
        });
    },
    
    /**
     * 显示导入V2Ray链接弹窗
     */
    showImportV2RayModal: function() {
        const formHtml = `
            <div style="padding: 20px;">
                <form class="layui-form" id="import-proxy-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">代理链接</label>
                        <div class="layui-input-block">
                            <textarea name="proxy_link" placeholder="请粘贴 vmess://, vless:// 或 trojan:// 链接" class="layui-textarea" rows="4"></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-top: 10px;">
                        <div class="layui-input-block">
                            <div class="layui-text" style="color: #999; font-size: 12px; line-height: 1.6;">
                                <p><strong>支持的协议：</strong></p>
                                <ul style="margin: 5px 0; padding-left: 20px;">
                                    <li>VMess: <code>vmess://base64编码</code></li>
                                    <li>VLESS: <code>vless://uuid@host:port?参数</code></li>
                                    <li>Trojan: <code>trojan://password@host:port?参数</code></li>
                                    <li>Shadowsocks: <code>ss://base64编码</code></li>
                                    <li>Hysteria: <code>hysteria://...</code></li>
                                    <li>Hysteria2: <code>hysteria2://...</code></li>
                                </ul>
                                <p style="margin-top: 10px; color: #FF5722;"><strong>注意：</strong>使用代理链接需要先安装Sing-box内核</p>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        `;
        
        const width = window.innerWidth;
        const isMobileOrTablet = width <= 1400;
        
        layer.open({
            type: 1,
            title: '导入代理链接',
            content: formHtml,
            area: isMobileOrTablet ? ['100%', '100%'] : ['600px', 'auto'],
            btn: ['导入', '取消'],
            btnAlign: 'c',
            yes: function(index) {
                // 直接获取textarea的值，不依赖layui表单
                const proxyLink = document.querySelector('#import-proxy-form textarea[name="proxy_link"]').value;
                ProxyModule.handleImportV2Ray(proxyLink, index);
            },
            success: function() {
                layui.form.render(null, 'import-proxy-form');
            }
        });
    },
    
    /**
     * 处理导入V2Ray链接
     */
    handleImportV2Ray: async function(proxyLink, layerIndex) {
        // 去除首尾空格
        const link = proxyLink ? proxyLink.trim() : '';
        
        console.log('导入代理链接:', link);
        
        if (!link) {
            layer.msg('请输入V2Ray链接', { icon: 2 });
            return;
        }
        
        // 验证链接格式
        const supportedProtocols = ['vmess://', 'vless://', 'trojan://', 'ss://', 'hysteria://', 'hysteria2://'];
        const isValidProtocol = supportedProtocols.some(protocol => link.startsWith(protocol));
        
        if (!isValidProtocol) {
            layer.msg('链接格式错误，支持的协议: VMess, VLESS, Trojan, Shadowsocks, Hysteria, Hysteria2', { icon: 2 });
            return;
        }
        
        const loadingIndex = layer.msg('正在解析链接...', { icon: 16, time: 0 });
        try {
            const response = await Api.apiRequest('/proxies/import-v2ray', {
                method: 'POST',
                body: JSON.stringify({ v2ray_link: link })
            });
            
            layer.close(loadingIndex);
            if (layerIndex) {
                layer.close(layerIndex);
            }
            layer.msg(response.msg || '导入成功', { icon: 1 });
            // 刷新列表
            this.refreshProxyList();
        } catch (error) {
            layer.close(loadingIndex);
            console.error('导入失败:', error);
            layer.msg('导入失败: ' + (error.detail || error.message), { icon: 2, time: 3000 });
        }
    },
    
    /**
     * 显示Sing-box管理界面
     */
    showSingboxManagement: async function() {
        const loadingIndex = layer.msg('正在加载...', { icon: 16, time: 0 });
        try {
            // 获取Sing-box状态
            const statusData = await Api.apiRequest('/singbox/status');
            const status = statusData || {};
            
            layer.close(loadingIndex);
            
            const html = this.renderSingboxManagementUI(status);
            
            const width = window.innerWidth;
            const isMobileOrTablet = width <= 1400;
            
            layer.open({
                type: 1,
                title: 'Sing-box内核管理',
                content: html,
                area: isMobileOrTablet ? ['100%', '100%'] : ['700px', 'auto'],
                btn: ['刷新状态', '关闭'],
                btnAlign: 'c',
                yes: function(index, layero) {
                    // 刷新状态
                    ProxyModule.refreshSingboxStatus(layero);
                    return false;
                },
                success: function(layero) {
                    // 绑定Sing-box操作事件
                    ProxyModule.bindSingboxEvents(layero);
                }
            });
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('加载Sing-box管理界面失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },
    
    /**
     * 渲染Sing-box管理界面
     */
    renderSingboxManagementUI: function(status) {
        const installed = status.installed || false;
        const version = status.version || '未安装';
        const path = status.path || '';
        const latestVersion = status.latest_version || '';
        
        let html = '<div style="padding: 20px;">';
        
        // 状态卡片
        html += '<div class="layui-card">';
        html += '<div class="layui-card-header">内核状态</div>';
        html += '<div class="layui-card-body">';
        html += '<table class="layui-table" lay-skin="nob">';
        html += '<tbody>';
        html += `<tr><td width="120"><strong>安装状态：</strong></td><td>`;
        if (installed) {
            html += '<span style="color: #5FB878;">● 已安装</span>';
        } else {
            html += '<span style="color: #FF5722;">● 未安装</span>';
        }
        html += '</td></tr>';
        html += `<tr><td><strong>当前版本：</strong></td><td>${escapeHtml(version)}</td></tr>`;
        if (latestVersion) {
            html += `<tr><td><strong>最新版本：</strong></td><td>${escapeHtml(latestVersion)}</td></tr>`;
        }
        if (path) {
            html += `<tr><td><strong>安装路径：</strong></td><td><code style="font-size: 12px;">${escapeHtml(path)}</code></td></tr>`;
        }
        html += '</tbody></table>';
        html += '</div></div>';
        
        if (installed) {
            // 已安装：显示操作按钮
            html += '<div style="margin-top: 20px; text-align: center;">';
            html += '<button class="layui-btn layui-btn-warm" id="singbox-test-btn"><i class="layui-icon layui-icon-test"></i> 测试连接</button> ';
            html += '<button class="layui-btn layui-btn-danger" id="singbox-uninstall-btn"><i class="layui-icon layui-icon-close"></i> 卸载内核</button>';
            html += '</div>';
        } else {
            // 未安装：显示下载安装说明
            html += '<div class="layui-card" style="margin-top: 15px;">';
            html += '<div class="layui-card-header"><i class="layui-icon layui-icon-tips"></i> 安装指南</div>';
            html += '<div class="layui-card-body">';
            
            // 什么是Sing-box
            html += '<div style="margin-bottom: 20px;">';
            html += '<p style="font-weight: bold; color: #333; margin-bottom: 8px;">什么是Sing-box？</p>';
            html += '<p style="color: #666; line-height: 1.6;">Sing-box是一个通用代理平台，支持VMess、VLESS、Trojan、Shadowsocks、Hysteria2等多种协议，比Xray更轻量高效。</p>';
            html += '</div>';
            
            // 下载信息
            html += '<div style="background: #f8f8f8; padding: 15px; border-radius: 4px; margin-bottom: 15px;">';
            html += '<p style="font-weight: bold; color: #333; margin-bottom: 10px;"><i class="layui-icon layui-icon-download-circle" style="color: #1E9FFF;"></i> 下载地址</p>';
            html += '<div style="text-align: center; margin: 15px 0;">';
            html += '<a href="https://github.com/SagerNet/sing-box/releases/latest" target="_blank" class="layui-btn layui-btn-normal">';
            html += '<i class="layui-icon layui-icon-link"></i> 打开GitHub下载页面</a>';
            html += '</div>';
            html += '<p style="color: #666; font-size: 13px; line-height: 1.6;">请在GitHub Releases页面下载最新稳定版本，选择对应系统的压缩包（约8-12MB）</p>';
            html += '</div>';
            
            // 安装步骤
            html += '<div style="background: #fff9e6; padding: 15px; border-radius: 4px; border-left: 3px solid #FFB800;">';
            html += '<p style="font-weight: bold; color: #333; margin-bottom: 10px;"><i class="layui-icon layui-icon-list" style="color: #FFB800;"></i> 安装步骤</p>';
            html += '<ol style="margin: 0; padding-left: 20px; color: #666; line-height: 1.8; font-size: 13px;">';
            html += '<li>点击上方按钮打开GitHub Releases页面</li>';
            html += '<li>在Assets列表中找到对应系统的压缩包文件</li>';
            html += '<li>下载到本地（<strong style="color: #FF5722;">不要解压</strong>）</li>';
            html += '<li>点击下方"上传安装"按钮</li>';
            html += '<li>选择下载的ZIP文件进行安装</li>';
            html += '</ol>';
            html += '</div>';
            
            html += '</div></div>';
            
            // 上传安装按钮
            html += '<div style="margin-top: 20px; text-align: center;">';
            html += '<button class="layui-btn layui-btn-lg layui-btn-normal" id="singbox-upload-btn">';
            html += '<i class="layui-icon layui-icon-upload"></i> 上传安装</button>';
            html += '</div>';
            
            // 注意事项
            html += '<div style="margin-top: 15px; padding: 10px; background: #fff0f0; border-radius: 4px; text-align: center;">';
            html += '<p style="color: #FF5722; font-size: 13px; margin: 0;"><i class="layui-icon layui-icon-tips"></i> 安装操作需要管理员权限</p>';
            html += '</div>';
        }
        
        html += '</div>';
        return html;
    },
    
    /**
     * 绑定Sing-box操作事件
     */
    bindSingboxEvents: function(layero) {
        // 上传安装按钮
        layero.find('#singbox-upload-btn').off('click').on('click', function() {
            ProxyModule.showUploadDialog(layero);
        });
        
        // 卸载按钮
        layero.find('#singbox-uninstall-btn').off('click').on('click', function() {
            ProxyModule.uninstallSingbox(layero);
        });
        
        // 测试按钮
        layero.find('#singbox-test-btn').off('click').on('click', function() {
            ProxyModule.testSingbox();
        });
    },
    
    /**
     * 显示上传对话框
     */
    showUploadDialog: function(parentLayero) {
        const html = `
            <div style="padding: 20px;">
                <div class="layui-upload">
                    <button type="button" class="layui-btn" id="singbox-select-file-btn">
                        <i class="layui-icon layui-icon-upload"></i> 选择压缩文件
                    </button>
                    <input type="file" id="singbox-file-input" accept=".zip,.tar.gz,.tgz,.tar" style="display: none;">
                    <div id="selected-file-info" style="margin-top: 15px; color: #666;"></div>
                </div>
                <div style="margin-top: 15px; padding: 10px; background: #f2f2f2; border-radius: 4px; font-size: 12px; color: #666;">
                    <p style="margin: 5px 0;">✓ 支持ZIP或TAR.GZ格式</p>
                    <p style="margin: 5px 0;">✓ 文件大小约8-12MB</p>
                    <p style="margin: 5px 0;">✓ 请确保是对应系统版本</p>
                </div>
            </div>
        `;
        
        const uploadIndex = layer.open({
            type: 1,
            title: '上传Sing-box安装包',
            content: html,
            area: ['450px', 'auto'],
            btn: ['开始安装', '取消'],
            btnAlign: 'c',
            yes: function() {
                ProxyModule.handleSingboxUpload(uploadIndex, parentLayero);
            },
            success: function() {
                // 绑定文件选择
                $('#singbox-select-file-btn').on('click', function() {
                    $('#singbox-file-input').click();
                });
                
                $('#singbox-file-input').on('change', function() {
                    const file = this.files[0];
                    if (file) {
                        $('#selected-file-info').html(`
                            <p style="color: #5FB878;"><i class="layui-icon layui-icon-ok-circle"></i> 已选择文件</p>
                            <p style="margin-top: 5px;">文件名：${escapeHtml(file.name)}</p>
                            <p>大小：${(file.size / 1024 / 1024).toFixed(2)} MB</p>
                        `);
                    }
                });
            }
        });
    },
    
    /**
     * 处理Sing-box文件上传
     */
    handleSingboxUpload: async function(uploadLayerIndex, parentLayero) {
        const fileInput = document.getElementById('singbox-file-input');
        const file = fileInput ? fileInput.files[0] : null;
        
        if (!file) {
            layer.msg('请先选择文件', { icon: 2 });
            return;
        }
        
        // 支持多种压缩格式
        const allowedExtensions = ['.zip', '.tar.gz', '.tgz', '.tar'];
        const isValidFile = allowedExtensions.some(ext => file.name.endsWith(ext));
        
        if (!isValidFile) {
            layer.msg('仅支持ZIP、TAR.GZ或TAR格式', { icon: 2 });
            return;
        }
        
        layer.close(uploadLayerIndex);
        const loadingIndex = layer.msg('正在上传安装，请稍候...', { icon: 16, time: 0, shade: 0.3 });
        
        try {
            const formData = new FormData();
            formData.append('file', file);
            
            const token = localStorage.getItem('token');
            const response = await fetch('/api/singbox/upload', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            });
            
            const result = await response.json();
            layer.close(loadingIndex);
            
            console.log('上传响应:', result);
            
            // 检查响应格式：后端返回 {success: true/false, msg: string, data: any}
            if (result.success) {
                layer.msg(result.msg || '安装成功', { icon: 1, time: 2000 });
                // 延迟刷新状态，让后端有时间完成安装
                setTimeout(() => {
                    ProxyModule.refreshSingboxStatus(parentLayero);
                }, 1000);
            } else {
                layer.msg(result.msg || '安装失败', { icon: 2, time: 3000 });
            }
        } catch (error) {
            layer.close(loadingIndex);
            console.error('上传失败:', error);
            layer.msg('上传失败: ' + error.message, { icon: 2, time: 3000 });
        }
    },
    
    /**
     * 卸载Sing-box
     */
    uninstallSingbox: async function(layero) {
        layer.confirm('确定要卸载Sing-box内核吗？<br><br>卸载后将无法使用V2Ray代理', {
            icon: 3,
            title: '确认卸载'
        }, async function(index) {
            layer.close(index);
            
            const loadingIndex = layer.msg('正在卸载...', { icon: 16, time: 0 });
            
            try {
                const response = await Api.apiRequest('/singbox/uninstall', {
                    method: 'DELETE'
                });
                
                layer.close(loadingIndex);
                layer.msg(response.msg || '卸载成功', { icon: 1 });
                
                // 刷新Sing-box状态
                setTimeout(() => {
                    ProxyModule.refreshSingboxStatus(layero);
                }, 500);
            } catch (error) {
                layer.close(loadingIndex);
                layer.msg('卸载失败: ' + (error.detail || error.message), { icon: 2 });
            }
        });
    },
    
    /**
     * 测试Sing-box
     */
    testSingbox: async function() {
        const loadingIndex = layer.msg('正在测试...', { icon: 16, time: 0 });
        try {
            const response = await Api.apiRequest('/singbox/status');
            layer.close(loadingIndex);
            
            if (response.installed) {
                layer.msg(`Sing-box运行正常<br>版本: ${response.version}`, { icon: 1, time: 3000 });
            } else {
                layer.msg('Sing-box未安装', { icon: 2 });
            }
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('测试失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },
    
    /**
     * 刷新Sing-box状态
     */
    refreshSingboxStatus: async function(layero) {
        const loadingIndex = layer.msg('刷新中...', { icon: 16, time: 0 });
        try {
            const statusData = await Api.apiRequest('/singbox/status');
            const status = statusData || {};
            
            layer.close(loadingIndex);
            
            const html = this.renderSingboxManagementUI(status);
            layero.find('.layui-layer-content').html(html);
            
            // 重新绑定事件
            this.bindSingboxEvents(layero);
            
            layer.msg('刷新成功', { icon: 1, time: 1000 });
        } catch (error) {
            layer.close(loadingIndex);
            layer.msg('刷新失败: ' + (error.detail || error.message), { icon: 2 });
        }
    }
};